function [lpostd,flag_ok]= ...
    lmjPosteriorOptimization(parest,Y,funcModel,solveOpt,addSol,prpar,prss,flag_transform,StIn) 
% =========================================================================
% PosteriorOptimization.M
%
% Structure 
% StIn.parVec        % Parameter Vector with calibrated positions In 
% StIn.parPosEst     % Position of the estimated parameters 
% stIn.transMat      % Transformation Matrix for estimation Parameters Only
% 
% stIn.trainVec      % trainVec training vector 

% CENTRAL since it allows for time aggregation issues, using same set-up as
% LMJ_LIKEL_CENTRAL.m 
%
% [lpostd,flag_ok]= lmj_postoptim_central(parest, StIn.parvec, StIn.parPosEst,
% StIn.transMat, StIn.funcModel, Y, StIn.trainVec, prpar, prss, solveopt, addsol, StIn.ssPosEst, flag_transform)
%
% LPOSTD        == 1e20 if there are problems 
% FLAG_OK       ==0 if there are problems 
%               Different from FLAG_LIKELOK, from all likelihood
%               optimization routines 
%
% Follows the structure of GENSYSPOST_VEC by Alejandro Justiniano (C)
% IN addition to putting priors on parameters, our current model put
% priors on steady state values.
%
% LIKEL: Default value for problems is 1e40 
% =======================================================================
lpostd=1e20;flag_ok=0;
%% 1. Transform to go from MIN to MOD
if flag_transform ==1
    parest=feval(@min2mod,parest,StIn.transMat);
    %[parest,flag_c]=feval(@check_min,parest,StIn.transMat);
    %if flag_c==0;disp('Problems with transformed coefficients');return;end
end
%printcell(num2cprec(parest)); 
%% 2. Fill in the vector and compute the Likelihood
StIn.parVec(StIn.parPosEst)=parest;
try
[likel,ssvec,flagOK]=...
    feval(addSol.funcLikel,parest,StIn.parVec,StIn.parPosEst,funcModel,Y,StIn.trainVec,...
    solveOpt,addSol);
catch
    disp('Error in lmjPosteriorOptimization')
    lasterr
    flagOK=0;
    return
end    
%dispaj(likel);
if flagOK==0;  
    return
end
if isinf(abs(likel));
    disp('Likelihood is infinite!')
    return
end
%% 3. Prior Density of Parameters
lpriord=sum(feval(@priordens,StIn.parVec, prpar.prior, prpar.alphap, prpar.betap, prpar.lbnd, prpar.ubnd));
if isinf(abs(lpriord))==1;return;end
%% 4. Prior Density on Steady State
if ~isempty(StIn.ssPosEst)
    lpriord_ss = sum(feval(@priordens,ssvec(StIn.ssPosEst), prss.prior, prss.alphap, prss.betap, prss.lbnd, prss.ubnd));
    if isinf(abs(lpriord_ss))==1;return;end
else
    lpriord_ss=0;
end
%% 5. Log Posterior
lpostd=-(lpriord + lpriord_ss + likel);
flag_ok=1; 
